home *** CD-ROM | disk | FTP | other *** search
/ Freelog 125 / Freelog_MarsAvril2015_No125.iso / Musique / Quod Libet / quodlibet-3.3.0-portable.exe / quodlibet-3.3.0-portable / data / bin / tokenize.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2014-12-31  |  14KB  |  424 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.7)
  3.  
  4. '''Tokenization help for Python programs.
  5.  
  6. generate_tokens(readline) is a generator that breaks a stream of
  7. text into Python tokens.  It accepts a readline-like method which is called
  8. repeatedly to get the next line of input (or "" for EOF).  It generates
  9. 5-tuples with these members:
  10.  
  11.     the token type (see token.py)
  12.     the token (a string)
  13.     the starting (row, column) indices of the token (a 2-tuple of ints)
  14.     the ending (row, column) indices of the token (a 2-tuple of ints)
  15.     the original line (string)
  16.  
  17. It is designed to match the working of the Python tokenizer exactly, except
  18. that it produces COMMENT tokens for comments and gives type OP for all
  19. operators
  20.  
  21. Older entry points
  22.     tokenize_loop(readline, tokeneater)
  23.     tokenize(readline, tokeneater=printtoken)
  24. are the same, except instead of generating tokens, tokeneater is a callback
  25. function to which the 5 fields described above are passed as 5 arguments,
  26. each time a new token is found.'''
  27. __author__ = 'Ka-Ping Yee <ping@lfw.org>'
  28. __credits__ = 'GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, Skip Montanaro, Raymond Hettinger'
  29. import string
  30. import re
  31. from token import *
  32. import token
  33. __all__ = [ x for x in dir(token) if x.startswith('_') ]
  34. __all__ += [
  35.     'COMMENT',
  36.     'tokenize',
  37.     'generate_tokens',
  38.     'NL',
  39.     'untokenize']
  40. del x
  41. del token
  42. COMMENT = N_TOKENS
  43. tok_name[COMMENT] = 'COMMENT'
  44. NL = N_TOKENS + 1
  45. tok_name[NL] = 'NL'
  46. N_TOKENS += 2
  47.  
  48. def group(*choices):
  49.     return '(' + '|'.join(choices) + ')'
  50.  
  51.  
  52. def any(*choices):
  53.     return group(*choices) + '*'
  54.  
  55.  
  56. def maybe(*choices):
  57.     return group(*choices) + '?'
  58.  
  59. Whitespace = '[ \\f\\t]*'
  60. Comment = '#[^\\r\\n]*'
  61. Ignore = Whitespace + any('\\\\\\r?\\n' + Whitespace) + maybe(Comment)
  62. Name = '[a-zA-Z_]\\w*'
  63. Hexnumber = '0[xX][\\da-fA-F]+[lL]?'
  64. Octnumber = '(0[oO][0-7]+)|(0[0-7]*)[lL]?'
  65. Binnumber = '0[bB][01]+[lL]?'
  66. Decnumber = '[1-9]\\d*[lL]?'
  67. Intnumber = group(Hexnumber, Binnumber, Octnumber, Decnumber)
  68. Exponent = '[eE][-+]?\\d+'
  69. Pointfloat = group('\\d+\\.\\d*', '\\.\\d+') + maybe(Exponent)
  70. Expfloat = '\\d+' + Exponent
  71. Floatnumber = group(Pointfloat, Expfloat)
  72. Imagnumber = group('\\d+[jJ]', Floatnumber + '[jJ]')
  73. Number = group(Imagnumber, Floatnumber, Intnumber)
  74. Single = "[^'\\\\]*(?:\\\\.[^'\\\\]*)*'"
  75. Double = '[^"\\\\]*(?:\\\\.[^"\\\\]*)*"'
  76. Single3 = "[^'\\\\]*(?:(?:\\\\.|'(?!''))[^'\\\\]*)*'''"
  77. Double3 = '[^"\\\\]*(?:(?:\\\\.|"(?!""))[^"\\\\]*)*"""'
  78. Triple = group("[uUbB]?[rR]?'''", '[uUbB]?[rR]?"""')
  79. String = group("[uUbB]?[rR]?'[^\\n'\\\\]*(?:\\\\.[^\\n'\\\\]*)*'", '[uUbB]?[rR]?"[^\\n"\\\\]*(?:\\\\.[^\\n"\\\\]*)*"')
  80. Operator = group('\\*\\*=?', '>>=?', '<<=?', '<>', '!=', '//=?', '[+\\-*/%&|^=<>]=?', '~')
  81. Bracket = '[][(){}]'
  82. Special = group('\\r?\\n', '[:;.,`@]')
  83. Funny = group(Operator, Bracket, Special)
  84. PlainToken = group(Number, Funny, String, Name)
  85. Token = Ignore + PlainToken
  86. ContStr = group("[uUbB]?[rR]?'[^\\n'\\\\]*(?:\\\\.[^\\n'\\\\]*)*" + group("'", '\\\\\\r?\\n'), '[uUbB]?[rR]?"[^\\n"\\\\]*(?:\\\\.[^\\n"\\\\]*)*' + group('"', '\\\\\\r?\\n'))
  87. PseudoExtras = group('\\\\\\r?\\n|\\Z', Comment, Triple)
  88. PseudoToken = Whitespace + group(PseudoExtras, Number, Funny, ContStr, Name)
  89. (tokenprog, pseudoprog, single3prog, double3prog) = map(re.compile, (Token, PseudoToken, Single3, Double3))
  90. endprogs = {
  91.     "'": re.compile(Single),
  92.     '"': re.compile(Double),
  93.     "'''": single3prog,
  94.     '"""': double3prog,
  95.     "r'''": single3prog,
  96.     'r"""': double3prog,
  97.     "u'''": single3prog,
  98.     'u"""': double3prog,
  99.     "ur'''": single3prog,
  100.     'ur"""': double3prog,
  101.     "R'''": single3prog,
  102.     'R"""': double3prog,
  103.     "U'''": single3prog,
  104.     'U"""': double3prog,
  105.     "uR'''": single3prog,
  106.     'uR"""': double3prog,
  107.     "Ur'''": single3prog,
  108.     'Ur"""': double3prog,
  109.     "UR'''": single3prog,
  110.     'UR"""': double3prog,
  111.     "b'''": single3prog,
  112.     'b"""': double3prog,
  113.     "br'''": single3prog,
  114.     'br"""': double3prog,
  115.     "B'''": single3prog,
  116.     'B"""': double3prog,
  117.     "bR'''": single3prog,
  118.     'bR"""': double3prog,
  119.     "Br'''": single3prog,
  120.     'Br"""': double3prog,
  121.     "BR'''": single3prog,
  122.     'BR"""': double3prog,
  123.     'r': None,
  124.     'R': None,
  125.     'u': None,
  126.     'U': None,
  127.     'b': None,
  128.     'B': None }
  129. triple_quoted = { }
  130. for t in ("'''", '"""', "r'''", 'r"""', "R'''", 'R"""', "u'''", 'u"""', "U'''", 'U"""', "ur'''", 'ur"""', "Ur'''", 'Ur"""', "uR'''", 'uR"""', "UR'''", 'UR"""', "b'''", 'b"""', "B'''", 'B"""', "br'''", 'br"""', "Br'''", 'Br"""', "bR'''", 'bR"""', "BR'''", 'BR"""'):
  131.     triple_quoted[t] = t
  132.  
  133. single_quoted = { }
  134. for t in ("'", '"', "r'", 'r"', "R'", 'R"', "u'", 'u"', "U'", 'U"', "ur'", 'ur"', "Ur'", 'Ur"', "uR'", 'uR"', "UR'", 'UR"', "b'", 'b"', "B'", 'B"', "br'", 'br"', "Br'", 'Br"', "bR'", 'bR"', "BR'", 'BR"'):
  135.     single_quoted[t] = t
  136.  
  137. tabsize = 8
  138.  
  139. class TokenError(Exception):
  140.     pass
  141.  
  142.  
  143. class StopTokenizing(Exception):
  144.     pass
  145.  
  146.  
  147. def printtoken(type, token, srow_scol, erow_ecol, line):
  148.     (srow, scol) = srow_scol
  149.     (erow, ecol) = erow_ecol
  150.     print '%d,%d-%d,%d:\t%s\t%s' % (srow, scol, erow, ecol, tok_name[type], repr(token))
  151.  
  152.  
  153. def tokenize(readline, tokeneater = printtoken):
  154.     '''
  155.     The tokenize() function accepts two parameters: one representing the
  156.     input stream, and one providing an output mechanism for tokenize().
  157.  
  158.     The first parameter, readline, must be a callable object which provides
  159.     the same interface as the readline() method of built-in file objects.
  160.     Each call to the function should return one line of input as a string.
  161.  
  162.     The second parameter, tokeneater, must also be a callable object. It is
  163.     called once for each token, with five arguments, corresponding to the
  164.     tuples generated by generate_tokens().
  165.     '''
  166.     
  167.     try:
  168.         tokenize_loop(readline, tokeneater)
  169.     except StopTokenizing:
  170.         pass
  171.  
  172.  
  173.  
  174. def tokenize_loop(readline, tokeneater):
  175.     for token_info in generate_tokens(readline):
  176.         tokeneater(*token_info)
  177.     
  178.  
  179.  
  180. class Untokenizer:
  181.     
  182.     def __init__(self):
  183.         self.tokens = []
  184.         self.prev_row = 1
  185.         self.prev_col = 0
  186.  
  187.     
  188.     def add_whitespace(self, start):
  189.         (row, col) = start
  190.         if not row <= self.prev_row:
  191.             raise AssertionError
  192.         col_offset = None - self.prev_col
  193.         if col_offset:
  194.             self.tokens.append(' ' * col_offset)
  195.  
  196.     
  197.     def untokenize(self, iterable):
  198.         for t in iterable:
  199.             if len(t) == 2:
  200.                 self.compat(t, iterable)
  201.                 break
  202.             (tok_type, token, start, end, line) = t
  203.             self.add_whitespace(start)
  204.             self.tokens.append(token)
  205.             (self.prev_row, self.prev_col) = end
  206.             if tok_type in (NEWLINE, NL):
  207.                 self.prev_row += 1
  208.                 self.prev_col = 0
  209.                 continue
  210.         return ''.join(self.tokens)
  211.  
  212.     
  213.     def compat(self, token, iterable):
  214.         startline = False
  215.         indents = []
  216.         toks_append = self.tokens.append
  217.         (toknum, tokval) = token
  218.         if toknum in (NAME, NUMBER):
  219.             tokval += ' '
  220.         if toknum in (NEWLINE, NL):
  221.             startline = True
  222.         prevstring = False
  223.         for tok in iterable:
  224.             (toknum, tokval) = tok[:2]
  225.             if toknum in (NAME, NUMBER):
  226.                 tokval += ' '
  227.             if toknum == STRING:
  228.                 if prevstring:
  229.                     tokval = ' ' + tokval
  230.                 prevstring = True
  231.             else:
  232.                 prevstring = False
  233.             if toknum == INDENT:
  234.                 indents.append(tokval)
  235.                 continue
  236.             elif toknum == DEDENT:
  237.                 indents.pop()
  238.                 continue
  239.             elif toknum in (NEWLINE, NL):
  240.                 startline = True
  241.             elif startline and indents:
  242.                 toks_append(indents[-1])
  243.                 startline = False
  244.             toks_append(tokval)
  245.         
  246.  
  247.  
  248.  
  249. def untokenize(iterable):
  250.     '''Transform tokens back into Python source code.
  251.  
  252.     Each element returned by the iterable must be a token sequence
  253.     with at least two elements, a token number and token value.  If
  254.     only two tokens are passed, the resulting output is poor.
  255.  
  256.     Round-trip invariant for full input:
  257.         Untokenized source will match input source exactly
  258.  
  259.     Round-trip invariant for limited intput:
  260.         # Output text will tokenize the back to the input
  261.         t1 = [tok[:2] for tok in generate_tokens(f.readline)]
  262.         newcode = untokenize(t1)
  263.         readline = iter(newcode.splitlines(1)).next
  264.         t2 = [tok[:2] for tok in generate_tokens(readline)]
  265.         assert t1 == t2
  266.     '''
  267.     ut = Untokenizer()
  268.     return ut.untokenize(iterable)
  269.  
  270.  
  271. def generate_tokens(readline):
  272.     '''
  273.     The generate_tokens() generator requires one argment, readline, which
  274.     must be a callable object which provides the same interface as the
  275.     readline() method of built-in file objects. Each call to the function
  276.     should return one line of input as a string.  Alternately, readline
  277.     can be a callable function terminating with StopIteration:
  278.         readline = open(myfile).next    # Example of alternate readline
  279.  
  280.     The generator produces 5-tuples with these members: the token type; the
  281.     token string; a 2-tuple (srow, scol) of ints specifying the row and
  282.     column where the token begins in the source; a 2-tuple (erow, ecol) of
  283.     ints specifying the row and column where the token ends in the source;
  284.     and the line on which the token was found. The line passed is the
  285.     logical line; continuation lines are included.
  286.     '''
  287.     lnum = parenlev = continued = 0
  288.     namechars = string.ascii_letters + '_'
  289.     numchars = '0123456789'
  290.     (contstr, needcont) = ('', 0)
  291.     contline = None
  292.     indents = [
  293.         0]
  294.     while None:
  295.         
  296.         try:
  297.             line = readline()
  298.         except StopIteration:
  299.             line = ''
  300.  
  301.         lnum += 1
  302.         pos = 0
  303.         max = len(line)
  304.         if contstr:
  305.             if not line:
  306.                 raise TokenError, ('EOF in multi-line string', strstart)
  307.             endmatch = endprog.match(line)
  308.             if endmatch:
  309.                 pos = end = endmatch.end(0)
  310.                 yield (STRING, contstr + line[:end], strstart, (lnum, end), contline + line)
  311.                 (contstr, needcont) = ('', 0)
  312.                 contline = None
  313.             elif needcont and line[-2:] != '\\\n' and line[-3:] != '\\\r\n':
  314.                 yield (ERRORTOKEN, contstr + line, strstart, (lnum, len(line)), contline)
  315.                 contstr = ''
  316.                 contline = None
  317.                 continue
  318.             else:
  319.                 contstr = contstr + line
  320.                 contline = contline + line
  321.         elif parenlev == 0 and not continued:
  322.             if not line:
  323.                 break
  324.             column = 0
  325.             while pos < max:
  326.                 if line[pos] == ' ':
  327.                     column += 1
  328.                 elif line[pos] == '\t':
  329.                     column = (column // tabsize + 1) * tabsize
  330.                 elif line[pos] == '\x0c':
  331.                     column = 0
  332.                 else:
  333.                     break
  334.                 pos += 1
  335.             if pos == max:
  336.                 break
  337.             if line[pos] in '#\r\n':
  338.                 if line[pos] == '#':
  339.                     comment_token = line[pos:].rstrip('\r\n')
  340.                     nl_pos = pos + len(comment_token)
  341.                     yield (COMMENT, comment_token, (lnum, pos), (lnum, pos + len(comment_token)), line)
  342.                     yield (NL, line[nl_pos:], (lnum, nl_pos), (lnum, len(line)), line)
  343.                     continue
  344.                 yield ((NL, COMMENT)[line[pos] == '#'], line[pos:], (lnum, pos), (lnum, len(line)), line)
  345.                 continue
  346.             if column > indents[-1]:
  347.                 indents.append(column)
  348.                 yield (INDENT, line[:pos], (lnum, 0), (lnum, pos), line)
  349.             while column < indents[-1]:
  350.                 if column not in indents:
  351.                     raise IndentationError('unindent does not match any outer indentation level', ('<tokenize>', lnum, pos, line))
  352.                 indents = indents[:-1]
  353.                 yield (DEDENT, '', (lnum, pos), (lnum, pos), line)
  354.         elif not line:
  355.             raise TokenError, ('EOF in multi-line statement', (lnum, 0))
  356.         continued = 0
  357.         while pos < max:
  358.             pseudomatch = pseudoprog.match(line, pos)
  359.             if pseudomatch:
  360.                 (start, end) = pseudomatch.span(1)
  361.                 spos = (lnum, start)
  362.                 epos = (lnum, end)
  363.                 pos = end
  364.                 if start == end:
  365.                     continue
  366.                 token = line[start:end]
  367.                 initial = line[start]
  368.                 if (initial in numchars or initial == '.') and token != '.':
  369.                     yield (NUMBER, token, spos, epos, line)
  370.                 elif initial in '\r\n':
  371.                     yield (NL if parenlev > 0 else NEWLINE, token, spos, epos, line)
  372.                 elif initial == '#':
  373.                     if not not token.endswith('\n'):
  374.                         raise AssertionError
  375.                     yield (None, token, spos, epos, line)
  376.                 elif token in triple_quoted:
  377.                     endprog = endprogs[token]
  378.                     endmatch = endprog.match(line, pos)
  379.                     if endmatch:
  380.                         pos = endmatch.end(0)
  381.                         token = line[start:pos]
  382.                         yield (STRING, token, spos, (lnum, pos), line)
  383.                     else:
  384.                         strstart = (lnum, start)
  385.                         contstr = line[start:]
  386.                         contline = line
  387.                         break
  388.                 elif initial in single_quoted and token[:2] in single_quoted or token[:3] in single_quoted:
  389.                     if token[-1] == '\n':
  390.                         strstart = (lnum, start)
  391.                         if not endprogs[initial] and endprogs[token[1]]:
  392.                             pass
  393.                         endprog = endprogs[token[2]]
  394.                         contstr = line[start:]
  395.                         needcont = 1
  396.                         contline = line
  397.                         break
  398.                     else:
  399.                         yield (STRING, token, spos, epos, line)
  400.                 elif initial in namechars:
  401.                     yield (NAME, token, spos, epos, line)
  402.                 elif initial == '\\':
  403.                     continued = 1
  404.                 elif initial in '([{':
  405.                     parenlev += 1
  406.                 elif initial in ')]}':
  407.                     parenlev -= 1
  408.                 yield (OP, token, spos, epos, line)
  409.                 continue
  410.             yield (ERRORTOKEN, line[pos], (lnum, pos), (lnum, pos + 1), line)
  411.             pos += 1
  412.         continue
  413.         for indent in indents[1:]:
  414.             yield (DEDENT, '', (lnum, 0), (lnum, 0), '')
  415.         
  416.     yield (ENDMARKER, '', (lnum, 0), (lnum, 0), '')
  417.  
  418. if __name__ == '__main__':
  419.     import sys
  420.     if len(sys.argv) > 1:
  421.         tokenize(open(sys.argv[1]).readline)
  422.     else:
  423.         tokenize(sys.stdin.readline)
  424.